package com.itheima.rsa.filter;

import com.google.common.base.Charsets;
import com.itheima.rsa.RsaKeys;
import com.itheima.service.RsaService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RsaDecryotFilter extends ZuulFilter {
    @Autowired
    RsaService rsaService;
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        String date=null;
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        try {
            ServletInputStream inputStream = request.getInputStream();
            //获取在流中传输的数据
            String string = StreamUtils.copyToString(inputStream, Charsets.UTF_8);
            System.out.println(string);
            //将获取的字符串解密
            if(!StringUtils.isEmpty(string)){
                date = rsaService.RSADecryptDataPEM(string, RsaKeys.getServerPrvKeyPkcs8());
                System.out.println(date);
            }
            if(!StringUtils.isEmpty(date)){
                byte[] bytes = date.getBytes();
                requestContext.setRequest(new HttpServletRequestWrapper(request){
                    @Override
                    public ServletInputStream getInputStream() throws IOException {
                        //将解密后的数据传给输入流
                      return new ServletInputStreamWrapper(bytes);
                    }

                    @Override
                    public int getContentLength() {
                        return bytes.length;
                    }

                    @Override
                    public long getContentLengthLong() {
                        return bytes.length;
                    }
                });
            }
            //设置请求头为json
            requestContext.addZuulRequestHeader("Content-Type",
                    MediaType.APPLICATION_JSON_VALUE+";charset=utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
